package chixing.day20.work4;

import java.util.*;
import java.util.stream.Collectors;

public class DispatchService {
    private List<Rider> riders;
    private List<Order> pendingOrders;
    private Map<Rider, List<Order>> riderOrders; // 记录每个骑手的订单

    public DispatchService() {
        this.riders = new ArrayList<>();
        this.pendingOrders = new ArrayList<>();
        this.riderOrders = new HashMap<>();
    }

    // 添加骑手
    public void addRider(Rider rider) {
        riders.add(rider);
        riderOrders.put(rider, new ArrayList<>());
    }

    // 添加新订单
    public void addOrder(Order order) {
        pendingOrders.add(order);
        System.out.println("新订单加入系统: O" + String.format("%03d", order.getOrderId()) +
                ", 优先级: " + order.getOrderPriority());
    }

    // 智能派单
    public Rider dispatch(Order order) {
        // 获取可用骑手
        List<Rider> availableRiders = getAvailableRiders();
        if (availableRiders.isEmpty()) {
            System.out.println("订单ID: O" + String.format("%03d", order.getOrderId()) +
                    " 暂无可用骑手，进入等待队列");
            return null;
        }

        // 对可用骑手进行评分排序
        Rider bestRider = selectBestRider(availableRiders, order);

        if (bestRider != null) {
            // 分配订单给骑手
            bestRider.assignOrder();
            riderOrders.get(bestRider).add(order);
            order.startDelivery();

            System.out.println("订单ID: O" + String.format("%03d", order.getOrderId()) +
                    " 派给骑手: " + bestRider.getRiderName() +
                    ", 预计配送时间: " + order.getExpectedDeliveryTime() +
                    "分钟, 优先级: " + order.getOrderPriority());
            pendingOrders.remove(order);
        }

        return bestRider;
    }

    // 选择最佳骑手
    private Rider selectBestRider(List<Rider> availableRiders, Order order) {
        // 按优先级、距离、负载进行评分排序
        return availableRiders.stream()
                .sorted((r1, r2) -> {
                    // 优先级排序（高优先级优先）
                    int priorityCompare = order.getOrderPriority().compareTo(r1.getCurrentOrderCount() == 0 ?
                            OrderPriority.HIGH : OrderPriority.LOW);
                    if (priorityCompare != 0) return priorityCompare;

                    // 负载排序（负载低的优先）
                    int loadCompare = Integer.compare(r1.getCurrentOrderCount(), r2.getCurrentOrderCount());
                    if (loadCompare != 0) return loadCompare;

                    // 随机因素（处理评分相同的情况）
                    return new Random().nextBoolean() ? -1 : 1;
                })
                .findFirst()
                .orElse(null);
    }

    // 完成订单
    public void finishDelivery(Rider rider, Order order) {
        if (riderOrders.containsKey(rider) && riderOrders.get(rider).contains(order)) {
            order.completeDelivery();
            rider.completeOrder();
            riderOrders.get(rider).remove(order);

            System.out.println("骑手 " + rider.getRiderName() +
                    " 完成订单 O" + String.format("%03d", order.getOrderId()));
        }
    }

    // 查看骑手当前订单列表
    public List<Order> getOrdersByRider(Rider rider) {
        return new ArrayList<>(riderOrders.getOrDefault(rider, new ArrayList<>()));
    }

    // 查询空闲骑手
    public List<Rider> getAvailableRiders() {
        List<Rider> availableRiders = new ArrayList<>();
        for (Rider rider : riders) {
            if (rider.canAcceptOrder()) {
                availableRiders.add(rider);
            }
        }
        return availableRiders;
    }

    // 批量派单（按优先级排序后依次分配）
    public void batchDispatch() {
        // 按优先级排序订单
        List<Order> sortedOrders = pendingOrders.stream()
                .sorted((o1, o2) -> o2.getOrderPriority().compareTo(o1.getOrderPriority()))
                .collect(Collectors.toList());

        // 依次分配订单
        for (Order order : new ArrayList<>(sortedOrders)) {
            dispatch(order);
        }
    }

    // 获取待派单订单列表
    public List<Order> getPendingOrders() {
        return new ArrayList<>(pendingOrders);
    }

    // 输出每个骑手当前订单和完成订单总数
    public void printRiderStatistics() {
        System.out.println("\n=== 骑手统计信息 ===");
        for (Rider rider : riders) {
            List<Order> currentOrders = getOrdersByRider(rider);
            System.out.println("骑手: " + rider.getRiderName() +
                    ", 当前订单数: " + currentOrders.size() +
                    ", 当前负载: " + rider.getCurrentOrderCount() +
                    "/" + rider.getRiderMaxCapacity());
            if (!currentOrders.isEmpty()) {
                System.out.print("  当前订单: ");
                for (int i = 0; i < currentOrders.size(); i++) {
                    if (i > 0) System.out.print(", ");
                    System.out.print("O" + String.format("%03d", currentOrders.get(i).getOrderId()));
                }
                System.out.println();
            }
        }
    }
}
